package com.rogchen.learning.hystrinxclient;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.Test;

import java.util.Date;
import java.util.concurrent.*;

/**
 * @author Rogchen  rogchen128@gmail.com
 * @description:
 * @product: IntelliJ IDEA
 * @create by 20-3-24 10:38
 **/
public class 并发测试 {

    @Test
    public void 测试信号量() throws InterruptedException {
        int threadTotal = 20, clientTotal = 100;
        ExecutorService executorService = Executors.newCachedThreadPool();
//        定义信号量
        final Semaphore semaphore = new Semaphore(threadTotal);
//        定义信号枪-->countDown为0时才执行awit方法，保证主线程的等待
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        System.out.println("当前时间：" + new Date().toLocaleString());
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
//                    一次只允许进入一个，多余的会等待
                    semaphore.acquire();
                    // 判断是否正常
//                    System.out.println("当前线程：" + Thread.currentThread().getName());
                    OkHttpClient client = new OkHttpClient.Builder()
                            .readTimeout(10, TimeUnit.SECONDS)
                            .connectTimeout(10,TimeUnit.SECONDS)
                            .build();
                    Request request = new Request.Builder()
                            .get()
                            .url("http://localhost:9091/test")
                            .build();
                    if (request.isHttps()) {
                        System.out.println("this is https");
                    }
                    Response response = client.newCall(request).execute();
//                    String result = HttpClientUtil.doGet("http://localhost:9091/test");
                    System.out.println("response结果："+response.toString());
                    String result = response.body().string();
                    System.out.println(result);
//                    睡眠2秒
//                    TimeUnit.SECONDS.sleep(2);
                    semaphore.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println("结束时间：" + new Date().toLocaleString());
    }
}
